package com.homegoods.resource.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.homegoods.resource.R;

/**
 * @author QiQi
 * @ClassName: AddAndReduceWidget
 * @date 2018/10/6
 * @description 增加减少按钮控件
 */
public class AddAndReduceWidget extends LinearLayout implements View.OnClickListener {

    private int mCount = 1;
    private int kuCun = Integer.MAX_VALUE;
    private TextView tvCount;
    private OnCallBack onCallBack;

    public AddAndReduceWidget(@NonNull Context context) {
        this(context, null);
    }

    public AddAndReduceWidget(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AddAndReduceWidget(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View view = LayoutInflater.from(context).inflate(R.layout.add_reduce_layout, this, true);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        tvCount = findViewById(R.id.count);
        findViewById(R.id.add).setOnClickListener(this);
        findViewById(R.id.cut).setOnClickListener(this);
    }

    public void setOnCallBack(OnCallBack onCallBack) {
        this.onCallBack = onCallBack;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.add) {
            onAddClicked(v);
        } else if (v.getId() == R.id.cut) {
            onCutClicked(v);
        }
    }

    /**
     * 增加购买数量
     *
     * @param view
     */
    void onAddClicked(View view) {
        mCount++;
        if (mCount > kuCun) {
            mCount = kuCun;
        }
        tvCount.setText(String.valueOf(mCount));
        if (onCallBack != null) {
            onCallBack.result(this, mCount);
        }
    }

    /**
     * 减少购买数量
     *
     * @param view
     */
    void onCutClicked(View view) {
        if (mCount == 1) {
            return;
        }
        mCount--;
        if (mCount < 1) {
            mCount = 1;
        }
        tvCount.setText(String.valueOf(mCount));
        if (onCallBack != null) {
            onCallBack.result(this, mCount);
        }
    }

    public void setCount(int count) {
        initDefaultCount(count);
    }

    /**
     * 初始化数量
     *
     * @param count
     */
    public void initDefaultCount(int count) {
        if (count < 1) {
            count = 1;
        }

        this.mCount = count;
        tvCount.setText(String.valueOf(mCount));
    }

    /**
     * 加减按钮结果回调
     */
    public interface OnCallBack {
        /**
         * 设置结果
         *
         * @param count
         */
        void result(View view, int count);
    }

}
